(function () {
    var core = ecui,
        dom = core.dom,
        ui = core.ui,
        util = core.util,
        ext = core.ext,
        esr = ecui.esr;
    /**
     * control
     * 编辑 新增行 - 按钮。
     */
    ext.addItem = {
        constructor: function (el, options) {
            this._sTarget = options.target;
            this._bIsTable = options.isTable;
            this._sContainer = options.container;
            this._sPosition = options.position;
            this._sName = options.name;
            this._bIsCopy = options.isCopy;
            this._oOptions = options;
        },
        Events: {
            click: function (event) {
                if (ecui.dispatchEvent(this, 'beforeAdd', event) === false) {
                    return;
                }
                var el = dom.create(this._bIsTable ? 'table' : 'div');
                if (this._bIsCopy) {
                    var form = this.getForm(),
                        data = {},
                        valid = ecui.esr.parseObject(form, data, false),
                        items = util.parseValue(this._sName, data),
                        tr = this.getParent(),
                        body = dom.parent(tr.getMain()),
                        trs = dom.children(body),
                        index = trs.indexOf(tr.getMain()),
                        item = items[index];

                    el.innerHTML = ecui.esr.getEngine().render(this._sTarget, { timestamp: Date.now(), NS: ecui.esr.getData('NS'), item: item });
                    el = dom.first(el);
                    if (this._bIsTable) {
                        el = dom.first(el);
                    }
                    dom.insertAfter(el, tr.getMain());
                    ecui.init(el);
                } else {
                    el.innerHTML = ecui.esr.getEngine().render(this._sTarget, { timestamp: Date.now(), NS: ecui.esr.getData('NS') });
                    if (this._sContainer) {
                        var container = ecui.$(this._sContainer);
                        if (container) {
                            el = dom.first(el);
                            if (this._bIsTable) {
                                el = dom.first(el);
                            }
                            switch (this._sPosition) {
                                case 'beforeBegin':
                                    dom.insertBefore(el, container);
                                    ecui.init(el);
                                    break;
                                case 'afterBegin':
                                    if (dom.first(container)) {
                                        dom.insertBefore(el, dom.first(container));
                                        ecui.init(el);
                                    } else {
                                        container.appendChild(el);
                                        ecui.init(el);
                                    }
                                    break;
                                case 'beforeEnd':
                                    if (dom.last(container)) {
                                        dom.insertAfter(el, dom.last(container));
                                        ecui.init(el);
                                    } else {
                                        container.appendChild(el);
                                        ecui.init(el);
                                    }
                                    break;
                                case 'afterEnd':
                                    dom.insertAfter(el, container);
                                    ecui.init(el);
                                    break;
                                default:
                                    break;
                            }
                        }
                    } else {
                        var parent = dom.parent(this.getMain());
                        el = dom.insertAfter(dom.first(el), parent);
                        ecui.init(el);
                    }
                }
                ecui.dispatchEvent(this, 'itemChange', event);   
            }
        }
    };

    /**
     * control
     * 编辑 删除行 - 按钮。
     */
    ext.deleteItem = {
        constructor: function (el, options) {
            this._bMust = !!options.must;
            this._oOptions = options;
        },
        Events: {
            click: function (event) {
              
                if (ecui.dispatchEvent(this, 'beforeDelete', event) === false) {
                    return;
                }
                var parent = this.getParent();
                    
                if (this._bMust) {
                    var children = dom.children(parent.getParent().getMain());

                    if (children.length <= 1) {
                        ecui.tip('warn', '至少保留一项');
                        return;
                    }
                }

                if (parent instanceof ui.Item) {
                    ecui.dispatchEvent(this, 'itemChange', event);
                    parent.getParent().remove(parent);
                } else {
                    parent = parent.getMain();
                    dom.remove(parent);
                    ecui.dispatchEvent(this, 'itemChange', event);
                    ecui.dispose(parent);
                }
            }
        }
    };

    /*
     * 切换费用时，计算费用总计
     * options    属性：
     * optId       操作的记录id
     * detailId    获取详情信息的记录id
     * url         获取详情信息的接口路径
     * container   dialog容器id
     * target      dialog 的 内容target 模板名称
     *
     */
    ext.calculateCost = {
        constructor: function (value, options) {
            this._sNum = value;
            this._oOptions = options;
        },
        Events: {
            itemChange: function () {
                ext.calculateCost.calculateCost.call(this);
            },
            change: function (event) {
                ext.calculateCost.calculateCost.call(this);
            },
            input: function (event) {
                ext.calculateCost.calculateCost.call(this);
            },
            ready: function () {
                util.timer(function () {
                    ext.calculateCost.calculateCost.call(this);
                }, 30, this);
            }
        },
        calculateCost: function () {

            var target = ecui.$('calculate_total_' + this._sNum);
            if (!target) {
                return;
            }
            var costTotal = target.querySelector('.cost-total');
            var loanTotal = target.querySelector('.loan-total');
            var borrowTotal = target.querySelector('.borrow-total');
            if (costTotal) {
                var cont = ecui.$('cost_cont_' + this._sNum);
                var items = [];
                var costAmount = 0;
                dom.children(cont).forEach(function (item, index) {
                    var title = item.querySelector('.info-title');
                    item = item.getControl()._oItem;
                    costAmount += +item.costAmount || +item.sumPrice;
                    title = dom.first(title);
                    var text = title.innerHTML.replace(/\d+/, '');
                    title.innerHTML = text + (index + 1);
                });
                costTotal.innerHTML = costAmount;
            }
            if (loanTotal) {
                var loan = ecui.get('loan-' + this._sNum);
                var loan = loan._eText.firstElementChild ? loan._eText.firstElementChild.getControl()._oItem : {};
                var borrowAmount = +loan.borrowAmount || 0;
                loanTotal.innerHTML = costAmount > borrowAmount ? borrowAmount : costAmount;
            }
            if (borrowTotal) {
                var borrowAmount = ecui.get('borrow-amount-' + this._sNum);
                borrowTotal.innerHTML = +borrowAmount.getValue() || 0;
            }
        }
    };

    /*
     * 保存options参数
     */
    ext.options = {
        constructor: function (value, options) {
            this._oOptions = options;
        }
    };
    /*
     * 保存一组数据
     */
    ext.value = {
        constructor: function (value) {
            this._sValue = value;
        }
    };

    ext.hidePopup = {
        constructor: function (value, options) {
            this._oOptions = options;
        },
        Events: {
            click: function (event) {
                this.getParent().hide();
            }
        }
    };

    ext.stopPropagation = {
        Events: {
            click: function (event) {
                event.stopPropagation();
            }
        }
    };

    /*
     * 点击打开弹框的 按钮，适用于  编辑信息、查看详情 弹窗打开按钮
     * options    属性：
     * optId       操作的记录id
     * detailId    获取详情信息的记录id
     * url         获取详情信息的接口路径
     * container   dialog容器id
     * target      dialog 的 内容target 模板名称
     *
     */
    ext.showselect = {
        constructor: function (value, options) {
            this._sView = value || 'single_select';
            this._oOptions = options;
        },
        Events: {
            click: function (event) {
                if (ecui.dispatchEvent(this, 'beforeShowSelect', event) === false) {
                    return;
                }
                event.stopPropagation();
                ecui.esr.showSelect(ecui.esr.getEngine().render(this._sView, {
                    'options': this._oOptions,
                    value: this.getFormValue()
                }), function (event) {
                    ecui.dispatchEvent(this, 'change', event);
                    if (this.getBody().classList.value.indexOf('placeholder') !== -1) {
                        ecui.dom.removeClass(this.getBody(), 'placeholder');
                    }
                }.bind(this), this._oOptions.title);

                if (ecui.dispatchEvent(this, 'afterShowSelect', event) === false) {
                    return;
                }
            }
        }
    };


    /*
     * 保存options参数
     */
    ext.options = {
        constructor: function (value, options) {
            this._oOptions = options;
        }
    };
    /*
     * 保存一组数据
     */
    ext.value = {
        constructor: function (value) {
            this._sValue = value;
        }
    };
    /**
     * control
     * 列表操作按钮
     * options    属性：
     * optId       奖品操作记录id
     * url         操作调用的接口路径
     * tip         提示信息
     * title       提示标题
     * content     提示内容
     *
     */
    ext.confirm = {
        constructor: function (el, options) {
            this._sUrl = options.url;
            this._sTip = options.tip;
            this._sOptId = options.optId;
            this._bNoConfirm = options.noConfirm;
            this._sMethod = options.method || 'JSON';
            this._bReload = !!options.reload;
            this._sTitle = options.title || '提醒';
            this._sContent = options.content || '确认处理这条数据？';
            this._sConfirmText = options.confirmText || '确定';
            this._sCancelText = options.cancelText || '取消';
            this._oOptions = options;
        },
        Events: {
            click: function (event) {
                event.stopPropagation();
                function confirmRequest(event) {
                    ecui.esr.request(
                        util.stringFormat('confirmData@{0} {1}{2}{3}', this._sMethod, this._sUrl, (this._sUrl.indexOf('?') > 0 ? '&' : '?'), this._sOptId ? 'id=' + this._sOptId : ''),
                        function () {
                            var code = ecui.esr.getData('confirmData_CODE');
                            var data = ecui.esr.getData('confirmData');

                            this._bSend = false;
                            if (code === 0) {
                                if (this.onsuccess) {
                                    this.onsuccess(data);
                                }
                                if (this._sTip) {
                                    ecui.tip('success', util.stringFormat(this._sTip, data.result));
                                }
                                if (!this._bReload) {
                                    history.go(-1);
                                }
                                util.timer(function () {
                                    // 清楚缓存刷新路由
                                    var routeName = ecui.esr.getLocation().split('~')[0];
                                    var route = ecui.esr.getRoute(routeName);
                                    delete route.CACHE
                                    ecui.esr.reload();
                                }, 30, this);

                                ecui.dispatchEvent(this, 'confirmSuccess', event);
                            }
                        }.bind(this),
                        function () {
                            this._bSend = false;
                        }.bind(this)
                    );
                }
                if (this._bSend) {
                    return;
                }
                if (this._bNoConfirm) {
                    confirmRequest.call(this, event);
                    return;
                }

                this._bSend = true;
                ecui.confirm(
                    this._sContent,
                    confirmRequest.bind(this),
                    function () {
                        this._bSend = false;
                    }.bind(this)
                );
            },
            onsuccess: util.blank
        }
    };

    // select 编辑项 跳转路由选择 扩展插件
    ext.showSelectRoute = {
        constructor: function (value, options) {
            this._sRoute = value;
        },
        Events: {
            click: function (event) {
                if (ecui.dispatchEvent(this, 'beforeShowSelectRoute', event) === false) {
                    return;
                }
                event.stopPropagation();
                
                var route = ecui.esr.getRoute(this._sRoute.split('~')[0]);
                route.owner = this;
                ecui.esr.findRoute(this).notleave = false;
                ecui.esr.redirect(this._sRoute + '~DENY_CACHE');

                if (ecui.dispatchEvent(this, 'afterShowSelectRoute', event) === false) {
                    return;
                }
            }
        }
    };
    ext.replaceLink = {
      
        Events: {
            click: function (event) {
                var href = dom.getAttribute(this.getMain(), 'href');
                if (href) {
                    location.replace(href);
                }
            }
        }
    }
}());